<template>
	<view class="modern-container">
		<!-- 背景装饰 -->
		<view class="bg-decoration">
			<view class="bg-circle bg-circle-1"></view>
			<view class="bg-circle bg-circle-2"></view>
			<view class="bg-circle bg-circle-3"></view>
		</view>
		
		<!-- 主内容区域 -->
		<view class="main-content">
			<!-- Logo和标题 -->
			<view class="header-section">
				
				<view class="welcome-text">欢迎回来</view>
				<view class="subtitle">登录您的账户继续购物</view>
			</view>
			
			<!-- 登录表单卡片 -->
			<view class="login-card">
				<!-- 登录方式切换标签 -->
				<view class="tab-container">
					<view
						class="tab-item"
						:class="{ 'active': login_type === 1 }"
						@click="authLogin"
					>
						授权登录
					</view>
					<view
						class="tab-item"
						:class="{ 'active': login_type === 2 }"
						@click="accountLogin"
					>
						账号密码登录
					</view>
				</view>
				
				<!-- 表单内容 -->
				<view class="form-container">
					<!-- 授权登录 -->
					<view class="form-content" v-if="login_type == 1">
						<!-- 添加占位空间使高度一致 -->
						<view style="height: 224rpx;"></view>
						
						<!-- 登录按钮 -->
						<button class="modern-button auth-button" @click="loginByAuth">
							<text class="button-text">微信授权登录</text>
						</button>
					</view>
					
					<!-- 账号密码登录 -->
					<view class="form-content" v-if="login_type == 2">
						<view class="input-group" :class="{ 'error-group': errors.phone }">
							<view class="input-wrapper">
								<input
									type="number"
									maxlength="11"
									v-model="phone"
									@input="inputChange"
									data-key="phone"
									class="modern-input"
									placeholder="请输入手机号码"
								/>
							</view>
							<text class="error-message" v-if="errors.phone">{{ errors.phone }}</text>
						</view>
						
						<view class="input-group" :class="{ 'error-group': errors.password }">
							<view class="input-wrapper">
								<input
									type="password"
									maxlength="20"
									v-model="password"
									@input="inputChange"
									data-key="password"
									class="modern-input"
									placeholder="请输入密码"
								/>
							</view>
							<text class="error-message" v-if="errors.password">{{ errors.password }}</text>
						</view>
						
						<!-- 登录按钮 -->
						<view class="button-container">
							<button class="modern-button" @click="goLogin" :loading="logining">
								<text class="button-text">{{ btnTxt }}</text>
							</button>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 商城信息 -->
			<view class="powered-by">
				<text class="powered-text">本商城由 SparkShop 强力驱动</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		BASE_URL
	} from '@/config/app';
	
	export default{
		data() {
			return {
				logining: false,
				loginTitle: '欢迎使用',
				login_type: 1, // 1: 授权登录, 2: 账号密码登录
				phone: '',
				password: '',
				btnTxt: '登录',
				// 表单验证错误信息
				errors: {
					phone: '',
					password: ''
				}
			}
		},
		onLoad(){
			
		},
		methods: {
			navBack(){
				uni.navigateBack();
			},
			// 返回首页
			goHome() {
				uni.switchTab({
					url: '/pages/index/index'
				});
			},
			// 切换到授权登录
			authLogin() {
				this.login_type = 1;
				this.clearErrors();
			},
			// 切换到账号密码登录
			accountLogin() {
				this.login_type = 2;
				this.clearErrors();
			},
			// 输入变化处理
			inputChange(e){
				const key = e.currentTarget.dataset.key;
				this[key] = e.detail.value;
				// 实时清除对应字段的错误信息
				if (this.errors[key]) {
					this.errors[key] = '';
				}
			},
			// 验证手机号格式
			validatePhone(phone) {
				const phoneRegex = /^1[3-9]\d{9}$/;
				return phoneRegex.test(phone);
			},
			// 验证密码强度
			validatePassword(password) {
				return password.length >= 6;
			},
			// 清空错误信息
			clearErrors() {
				this.errors = {
					phone: '',
					password: ''
				};
			},
			// 验证表单
			validateForm() {
				this.clearErrors();
				let isValid = true;
				
				// 验证手机号
				if (!this.phone) {
					this.errors.phone = '请输入手机号';
					isValid = false;
				} else if (!this.validatePhone(this.phone)) {
					this.errors.phone = '请输入正确的手机号格式';
					isValid = false;
				}
				
				// 验证密码
				if (!this.password) {
					this.errors.password = '请输入密码';
					isValid = false;
				} else if (!this.validatePassword(this.password)) {
					this.errors.password = '密码长度不能少于6位';
					isValid = false;
				}
				
				return isValid;
			},
			// 授权登录
			async loginByAuth() {
				let that = this;
				uni.showLoading({
					title: '登录中'
				});
				
				try {
					// 1. 先获取 wx.login 的 code
					const loginRes = await new Promise((resolve, reject) => {
						wx.login({
							success: resolve,
							fail: reject
						});
					});
					
					if (!loginRes.code) {
						throw new Error('获取登录凭证失败');
					}
					
					// 2. 调用后端接口进行登录
					const res = await that.$api.login.miniappAuth.post({
						login_code: loginRes.code,
						spId: uni.getStorageSync('spId') || ''
					});
					
					uni.hideLoading();
					
					if (res.code == 0) {
						that.$tool.msg(res.msg);
						setTimeout(async () => {
							try {
								// 使用统一的登录成功处理方法
								await that.handleLoginSuccess(res);
								uni.reLaunch({ url: '/pages/user/user' });
								that.loading = false;
							} catch (error) {
								console.error('微信授权登录处理失败:', error);
								that.$tool.msg('登录信息保存失败');
								that.loading = false;
							}
						}, 1000);
					} else {
						that.$tool.msg(res.msg || '登录失败');
					}
				} catch (error) {
					uni.hideLoading();
					console.error('微信授权登录失败:', error);
					that.$tool.msg('登录失败，请重试');
				}
			},
			// 账号密码登录
			async goLogin() {
				// 使用统一的表单验证
				if (!this.validateForm()) {
					return;
				}
				
				this.logining = true;
				try {
					const res = await this.$api.login.loginByAccount.post({
						phone: this.phone,
						password: this.password
					});
					
					if (res.code === 0) {
						// 处理登录成功
						await this.handleLoginSuccess(res);
					} else {
						this.$tool.msg(res.msg || '登录失败，请重试');
					}
				} catch (error) {
					console.error('登录请求失败:', error);
					this.$tool.msg('网络错误，请稍后重试');
				} finally {
					this.logining = false;
				}
			},
			// 处理登录成功
			async handleLoginSuccess(res) {
				// 设置store
				try {
					await this.$store.dispatch('app/login', res);
					
					// 根据平台跳转到首页
					// #ifdef APP-PLUS
					uni.switchTab({
						url: '/pages/index/index'
					});
					// #endif
					// #ifdef H5 || MP-WEIXIN
					this.$router.push({ path: '/' });
					// #endif
				} catch (storeError) {
					console.error('存储登录信息失败:', storeError);
					this.$tool.msg('登录信息保存失败');
				}
			}
		},

	}
</script>

<style lang='scss' scoped>
	page {
		background-color: #f4f4f4;
		min-height: 100vh;
	}
	
	.modern-container {
		min-height: 100vh;
		display: flex;
		align-items: flex-start;
		justify-content: center;
		padding: 40rpx 20rpx;
		position: relative;
		overflow: hidden;
		padding-top: 100rpx;
	}
	
	/* 添加红色弧度背景 */
	.modern-container::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 55%;
		background-color: #e93939;
		border-radius: 0 0 50% 50% / 0 0 20% 20%;
		z-index: 1;
	}
	
	// 移除背景装饰，保持简洁
	.bg-decoration {
		display: none;
	}
	
	// 主内容区域
	.main-content {
		width: 100%;
		max-width: 700rpx;
		z-index: 10;
		position: relative;
		margin-top: 180rpx;
	}
	
	// 头部区域
	.header-section {
		text-align: center;
		margin-bottom: 40rpx;
		
		.logo-container {
			margin-bottom: 20rpx;
			
			.logo-text {
				font-size: 64rpx;
				font-weight: bold;
				color: #ffffff;
				text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
				letter-spacing: 2rpx;
			}
		}
		
		.welcome-text {
			font-size: 48rpx;
			font-weight: 600;
			color: #ffffff;
			margin-bottom: 16rpx;
		}
		
		.subtitle {
			font-size: 28rpx;
			color: rgba(255, 255, 255, 0.9);
			line-height: 1.5;
		}
	}
	
	// 登录卡片
	.login-card {
		background: rgba(255, 255, 255, 0.98);
		backdrop-filter: blur(10rpx);
		border-radius: 20rpx;
		padding: 40rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.08);
		
		// 标签切换
		.tab-container {
			display: flex;
			margin-bottom: 40rpx;
			background: rgba(233, 57, 57, 0.08);
			border-radius: 16rpx;
			padding: 8rpx;
			
			.tab-item {
				flex: 1;
				text-align: center;
				padding: 20rpx 16rpx;
				font-size: 28rpx;
				color: #666;
				border-radius: 12rpx;
				transition: all 0.3s ease;
				cursor: pointer;
				position: relative;
				
				&.active {
					background: #e93939;
					color: #ffffff;
					font-weight: 600;
					box-shadow: 0 4rpx 12rpx rgba(233, 57, 57, 0.2);
				}
				
				&:not(.active):active {
					transform: scale(0.98);
				}
			}
		}
		
		// 表单容器
		.form-container {
			.form-content {
				.input-group {
					margin-bottom: 32rpx;
					
					&.error-group {
						.input-wrapper {
							border-color: #ff4757;
							box-shadow: 0 0 0 4rpx rgba(255, 71, 87, 0.1);
						}
					}
					
					.input-wrapper {
						display: flex;
						align-items: center;
						background: #f8f9fa;
						border: 2rpx solid transparent;
						border-radius: 16rpx;
						padding: 0 24rpx;
						transition: all 0.3s ease;
						height: 96rpx;
						
						&:focus-within {
							border-color: #e93939;
							background: #ffffff;
							box-shadow: 0 0 0 4rpx rgba(233, 57, 57, 0.1);
						}
						
						.modern-input {
							flex: 1;
							height: 100%;
							font-size: 30rpx;
							color: #333;
							background: transparent;
							border: none;
							outline: none;
							
							&::placeholder {
								color: #999;
							}
						}
					}
					
					.error-message {
						color: #ff4757;
						font-size: 24rpx;
						margin-top: 12rpx;
						padding-left: 24rpx;
						line-height: 1.4;
					}
				}
			}
			
			// 现代化按钮
			.modern-button {
				width: 80%;
				height: 96rpx;
				background: #e93939;
				border-radius: 16rpx;
				border: none;
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 0 8rpx 24rpx rgba(233, 57, 57, 0.3);
				transition: all 0.3s ease;
				position: relative;
				overflow: hidden;
				
				&::before {
					content: '';
					position: absolute;
					top: 0;
					left: -100%;
					width: 100%;
					height: 100%;
					background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
					transition: left 0.6s;
				}
				
				&:active::before {
					left: 100%;
				}
				
				&:active {
					transform: translateY(2rpx);
					box-shadow: 0 4rpx 12rpx rgba(233, 57, 57, 0.3);
				}
				
				.button-text {
					color: white;
					font-size: 32rpx;
					font-weight: 600;
					letter-spacing: 1rpx;
				}
			}
			
			// 授权登录按钮样式
			.auth-button {
				width: 80%;
				margin: 40rpx auto 0;
				display: block;
			}
			
			// 按钮容器
			.button-container {
				display: flex;
				justify-content: center;
				margin-top: 40rpx;
			}
		}
	}
	
	// 商城信息
	.powered-by {
		text-align: center;
		padding: 30rpx 20rpx 50rpx;
		
		.powered-text {
			color: #999;
			font-size: 24rpx;
			opacity: 0.8;
		}
	}
</style>
